<script setup lang="ts">
import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'

const message = useMessage()
const url = ref('')
const loading = ref(false)
const previewFrame = ref<HTMLIFrameElement | null>(null)
const previewContainer = ref<HTMLDivElement | null>(null)

const loadUrl = async () => {
  if (!url.value) {
    message.warning('请输入网页地址')
    return
  }

  loading.value = true
  try {
    if (previewFrame.value) {
      // 确保URL是以http或https开头
      const finalUrl = url.value.startsWith('http') ? url.value : 'https://' + url.value
      previewFrame.value.src = finalUrl
    }
  } catch (error) {
    message.error('加载网页失败')
  } finally {
    loading.value = false
  }
}

const captureAsImage = async () => {
  if (!previewFrame.value || !previewContainer.value) {
    message.error('预览区域未准备好')
    return
  }

  loading.value = true
  try {
    const canvas = await html2canvas(previewContainer.value, {
      useCORS: true,
      allowTaint: true,
      logging: false,
      scale: 2 // 提高清晰度
    })

    // 将canvas转换为图片并下载
    const link = document.createElement('a')
    link.download = 'webpage-capture.png'
    link.href = canvas.toDataURL('image/png')
    link.click()
    message.success('图片已开始下载')
  } catch (error) {
    message.error('截图失败，请检查网页是否加载完成')
  } finally {
    loading.value = false
  }
}

const captureAsPdf = async () => {
  if (!previewFrame.value || !previewContainer.value) {
    message.error('预览区域未准备好')
    return
  }

  loading.value = true
  try {
    const canvas = await html2canvas(previewContainer.value, {
      useCORS: true,
      allowTaint: true,
      logging: false,
      scale: 2
    })

    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF({
      orientation: canvas.width > canvas.height ? 'landscape' : 'portrait',
      unit: 'px',
      format: [canvas.width, canvas.height]
    })

    pdf.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height)
    pdf.save('webpage-capture.pdf')
    message.success('PDF已开始下载')
  } catch (error) {
    message.error('生成PDF失败，请检查网页是否加载完成')
  } finally {
    loading.value = false
  }
}

const handleFrameLoad = () => {
  loading.value = false
}
</script>

<template>
  <div class="p-4 mx-auto max-w-7xl">
    <n-card>
      <template #header>
        <div class="text-2xl font-bold">网页保存工具</div>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          将网页保存为图片或PDF格式，支持自定义网页地址
        </p>
      </template>

      <div class="space-y-6">
        <!-- 输入区域 -->
        <div class="flex gap-4">
          <n-input
            v-model:value="url"
            type="text"
            placeholder="请输入网页地址（例如：https://www.example.com）"
            :disabled="loading"
          />
          <n-button
            type="primary"
            :loading="loading"
            :disabled="!url"
            @click="loadUrl"
          >
            加载网页
          </n-button>
        </div>

        <!-- 预览和操作区域 -->
        <div class="space-y-4">
          <div class="flex justify-end gap-2">
            <n-button
              type="info"
              :disabled="loading || !url"
              @click="captureAsImage"
            >
              保存为图片
            </n-button>
            <n-button
              type="success"
              :disabled="loading || !url"
              @click="captureAsPdf"
            >
              保存为PDF
            </n-button>
          </div>

          <!-- 预览区域 -->
          <div
            ref="previewContainer"
            class="w-full overflow-hidden bg-white rounded-lg"
            style="height: 600px"
          >
            <iframe
              ref="previewFrame"
              class="w-full h-full border-0"
              @load="handleFrameLoad"
              sandbox="allow-same-origin allow-scripts"
            ></iframe>
          </div>
        </div>
      </div>
    </n-card>
  </div>
</template>

<style scoped>
:deep(iframe) {
  background: white;
}
</style> 